import type * as ts from 'typescript/lib/tsserverlibrary';
import {decorateWithTemplateLanguageService} from 'typescript-template-language-service-decorator';
import {TsTemplateTypescriptLanguageService} from "./ts-lang-service";

function init(modules: { typescript: typeof ts }) {
    return {
        create(info: ts.server.PluginCreateInfo) {
            const logger = info.project.projectService.logger;
            logger.info(`[DEBUG] 调用方法: create1112`);

            // const ls = info.languageService;

            // 2. 使用模板装饰器
            const decoratedLS = decorateWithTemplateLanguageService(
                modules.typescript,
                info.languageService,
                info.project,
                {},
                {tags: ['ts']}
            );

            // 3. 创建最终的代理
            const proxy: ts.LanguageService = Object.create(null);
            for (let k of Object.keys(decoratedLS) as Array<keyof ts.LanguageService>) {
                const x = decoratedLS[k]!;
                // @ts-expect-error - JS runtime trickery
                proxy[k] = (...args: Array<{}>) => {
                    try {
                        logger.info(`[DEBUG] 调用方法: ${k}`);
                        // @ts-expect-error
                        const result = x.apply(decoratedLS, args);
                        return result;
                    } catch (error) {
                        logger.info(`[DEBUG] 方法 ${k} 执行错误: ${error}`);
                        throw error;
                    }
                };
            }

            return proxy;
        }
    };
}

export = init;
